package com.mediastory.spsserver.event.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mediastory.spsserver.event.dao.EventDao;
import com.mediastory.spsserver.event.domain.Event;
import com.mediastory.spsserver.event.service.EventSvc;
import com.mediastory.spsserver.eventFile.dao.EventFileDao;
import com.mediastory.spsserver.eventFile.domain.EventFile;
import com.Ostermiller.util.Base64;

@Service
@Transactional
public class EventSvcImpl implements EventSvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	EventDao eventDao;
	
	@Autowired
	EventFileDao eventFileDao;
	
	public EventSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Event> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Event>) (eventDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("eventList", (List<Event>) (eventDao.SelectList(condition)));
		resultMap.put("eventListTotalCnt", (Integer) (eventDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Event findby(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return eventDao.select(condition);
	}

	@Override
	public Event add(Event event) throws Exception {
		// TODO Auto-generated method stub
		Event result = null;
		List<File> fileList = new Vector<File>();
		
		try {
			result = eventDao.insert(event);
			
			//파일 업로드
			MultipartFile mFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(event.getEventFiles() != null){
				EventFile eventFile = new EventFile();
				
				for(int i = 0;i<event.getEventFiles().size();i++){
					mFile = event.getEventFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
					if(mFile == null || mFile.getSize() == 0){
						continue;
					}
					
					fileType = event.getEventFileTypes()[i];
					fileData = event.getEventFileDatas()[i];
					fileSize = mFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(event.getName(), "utf-8")+Long.toString(time)));
					//업로드 경로
					String uploadDir = messages.getMessage("file.event.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.event.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("bigBanner")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_bigBanner."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else if(fileType.equals("smallBanner")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_smallBanner."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else if(fileType.equals("detail")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_detail."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else if(fileType.equals("mainImg")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_mainImg."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
						
						fileData = "E^linkUrl^date^"+event.getEmblems()[i-3];
					}else{
						continue;
					}
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					mFile.transferTo(file);
					
					fileList.add(file);
					
					//콘텐츠 파일 등록
					eventFile.setEventIdx(result.getIdx());
					eventFile.setCreatedId(result.getCreatedId());
					eventFile.setCreatedIp(result.getCreatedIp());
					eventFile.setFileUrl(url);
					eventFile.setFileSize(fileSize);
					eventFile.setFileType(fileType);
					eventFile.setFileData(fileData);
					eventFileDao.insert(eventFile);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return result;
	}

	@Override
	public Event modify(Event event) throws Exception {
		// TODO Auto-generated method stub
		List<File> fileList = new Vector<File>();
		
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("eventIdx", event.getIdx());

			//파일 업로드
			condition.put("modifiedId", event.getModifiedId());
			condition.put("modifiedIp", event.getModifiedIp());
			
			MultipartFile mFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;

			if(event.getEventFiles() != null){
				EventFile eventFile = new EventFile();
				
				for(int i = 0;i<event.getEventFiles().size();i++){
					mFile = event.getEventFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
	 				if(mFile == null || mFile.getSize() == 0){
						continue;
					}
					
					fileType = event.getEventFileTypes()[i];
					fileData = event.getEventFileDatas()[i];
					fileSize = mFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(event.getName(), "utf-8")+Long.toString(time)));
					//업로드 경로
					String uploadDir = messages.getMessage("file.event.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.event.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("bigBanner")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_bigBanner."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
						//기존 등록된 파일 데이터 삭제
						condition.put("fileType", "bigBanner");
						eventFileDao.delete(condition);
					}else if(fileType.equals("smallBanner")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_smallBanner."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
						//기존 등록된 파일 데이터 삭제
						condition.put("fileType", "smallBanner");
						eventFileDao.delete(condition);
					}else if(fileType.equals("detail")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_detail."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
						//기존 등록된 파일 데이터 삭제
						condition.put("fileType", "detail");
						eventFileDao.delete(condition);
					}else if(fileType.equals("mainImg")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_mainImg."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
						
						fileData = "E^linkUrl^date^"+event.getEmblems()[i-3];
					}else{
						continue;
					}

					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					mFile.transferTo(file);
					
					fileList.add(file);
					
					//파일 등록
					eventFile.setEventIdx(event.getIdx());
					eventFile.setCreatedId(event.getModifiedId());
					eventFile.setCreatedIp(event.getModifiedIp());
					eventFile.setFileUrl(url);
					eventFile.setFileSize(fileSize);
					eventFile.setFileType(fileType);
					eventFile.setFileData(fileData);
					eventFileDao.insert(eventFile);
				}
			}

			//메인 이미지 삭제
			Integer[] delIdx = event.getEventFileIdx();
			if(delIdx != null && delIdx.length > 0){
				condition.put("idx", delIdx);
				condition.put("fileType", "mainImg");
				eventFileDao.delete(condition);	
			}

			event = eventDao.update(event);
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return event;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return eventDao.delete(condition);
	}

	@Override
	public Integer findbyChkNm(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return eventDao.SelectListTotalCnt(condition);
	}

}